package com.gitee.zihaolicn;

import com.google.googlejavaformat.java.Formatter;
import com.google.googlejavaformat.java.FormatterException;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FormatJavaFile {
    public static void main(String[] args) {
        // 输入和输出文件路径
        String inputFilePath = "C:\\Users\\li003\\IdeaProjects\\RepoJavaDecompile\\src\\main\\java\\com\\gitee\\zihaolicn\\FormatJavaFile.java";
        String outputFilePath = "C:\\Users\\li003\\IdeaProjects\\RepoJavaDecompile\\src\\main\\java\\com\\gitee\\zihaolicn\\FormatJavaFile2.java";

        try {
            // 读取 Java 文件内容
            String sourceCode = new String(Files.readAllBytes(Paths.get(inputFilePath)));

            // 创建 Google Java Format 的 Formatter 实例
            Formatter formatter = new Formatter();

            // 格式化代码
            String formattedCode = formatter.formatSource(sourceCode);

            // 确保输出目录存在
            File outputFile = new File(outputFilePath);
            Files.createDirectories(Paths.get(outputFile.getParent()));

            // 写入格式化后的代码到输出文件
            Files.write(Paths.get(outputFilePath), formattedCode.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

            System.out.println("Java file formatted successfully. Output written to: " + outputFilePath);

        } catch (FormatterException e) {
            System.err.println("Error formatting file: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("Error processing file: " + e.getMessage());
            e.printStackTrace();
        }
    }
}